package com.oocl.batchdatav2.msghandler;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

import com.oocl.batchdatav2.command.Command;
import com.oocl.batchdatav2.command.impl.ConcreteCommand;
import com.oocl.batchdatav2.command.receiver.ListCommandReceiver;
import com.oocl.batchdatav2.command.receiver.WriteFileCommandReceiver;

public class MessageLooper {
	
	private InputStream in;
	private OutputStream out;
	
	public MessageLooper(InputStream in, OutputStream out) {
		this.in = in;
		this.out = out;
	}

	public void startLoop() throws Exception {
		out.write("Enter command > ".getBytes());
		
		BufferedReader reader = new BufferedReader(new InputStreamReader(in));
		boolean msgLoop = true;
		
		while (msgLoop) {
			String line = reader.readLine();
			String[] cmdSplit = line.split(" ");
			Command command = null;
			
			switch (cmdSplit[0]) {
			case "L":
				command = new ConcreteCommand(new ListCommandReceiver(cmdSplit));
				break;
			case "C":
				command = new ConcreteCommand(new WriteFileCommandReceiver(cmdSplit));
				break;
			case "Q":
				msgLoop = false;
				break;
			default:
				break;
			}
			
			if (msgLoop) {
				StringBuilder result = command == null ? new StringBuilder("Command error!") : command.execute();
				out.write(result.append("\r\n\r\nEnter command > ").toString().getBytes());
			} else {
				out.write("Bye.\r\n".getBytes());
			}
		}
	}
}
